<template>
  <div class="search">
    <Card>
      <Row>
        <Form ref="searchForm" inline :label-width="70" class="search-form">
          <FormItem label="装货地址">
            <div style="width: 200px">
              <Cascader
                class="Unloadingcss"
                v-model="searchForm.LoadingAddress"
                :data="UnloadingAddresslist"
                :load-data="LoadingProvinceloadData"
                @on-change="getStartArea"
                clearable
              ></Cascader>
            </div>
          </FormItem>
          <FormItem label="卸货地址">
            <div style="width: 200px">
              <Cascader
                class="Unloadingcss"
                v-model="searchForm.UnloadingAddress"
                :data="UnloadingAddresslist"
                :load-data="ProvinceloadData"
                @on-change="changeUnloading"
                clearable
              ></Cascader>
            </div>
          </FormItem>
          <FormItem label="选择月份">
            <DatePicker
              type="month"
              placeholder="请选择月份"
              style="width: 200px"
              v-model="month"
              @on-change="changeMonth"
            ></DatePicker>
          </FormItem>
          <FormItem style="margin-left: -35px" class="br">
            <Button @click="handleSearch" type="primary" icon="ios-search"
              >搜索</Button
            >
            <Button @click="handleReset">重置</Button>
            <Button @click="getDataList" icon="md-refresh">刷新</Button>
            <!-- <Button @click="exportSelectData" icon="md-cloud-upload"
              >导出所选数据</Button
            > -->
          </FormItem>
        </Form>
      </Row>

      <Row>
        <Table
          :loading="loading"
          border
          :columns="columns"
          :data="data"
          ref="table"
          @on-selection-change="changeSelect"
        ></Table>
      </Row>
      <Row type="flex" justify="end" class="page" style="margin-top: 2vh">
        <Page
          :current="searchForm.pageNumber"
          :total="total"
          :page-size="searchForm.pageSize"
          @on-change="changePage"
          @on-page-size-change="changePageSize"
          :page-size-opts="[10, 20, 50]"
          size="small"
          show-total
          show-elevator
          show-sizer
        ></Page>
      </Row>
    </Card>
    <!-- 自定义导出数据 -->
    <Modal
      v-model="exportModalVisible"
      :title="exportTitle"
      :loading="loadingExport"
      @on-ok="exportCustomData"
    >
      <Form ref="exportForm" :label-width="100">
        <FormItem label="导出文件名">
          <Input v-model="filename" />
        </FormItem>
        <FormItem label="自定义导出列">
          <CheckboxGroup v-model="chooseColumns">
            <Checkbox
              v-for="(item, i) in exportColumns"
              :label="item.title"
              :key="i"
              :value="item.checked"
              :disabled="item.disabled"
            ></Checkbox>
          </CheckboxGroup>
        </FormItem>
        <FormItem label="备注">
          <Input
            v-model="exportRemarks"
            placeholder="备注"
            style="width: 300px"
          />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
// 根据你的实际请求api.js位置路径修改
import excel from "@/libs/excel";
import {
  getProvinceData,
  getAreaCityList,
  addDownloadRecord,
} from "@/api/index";
import { getCityOrderSumVo, getAreaOrderSumVo } from "@/api/analyse";
export default {
  name: "orderAnalyse",
  data() {
    return {
      loading: false,
      month: "",
      begin: [],
      end: [],
      UnloadingAddresslist: [],
      searchForm: {
        // 搜索框初始化对象
        LoadingAddress: "",
        UnloadingAddress: "",
        pageNumber: 1, // 当前页数
        pageSize: 10, // 页面大小
        beginAreaCode: "",
        endAreaCode: "",
        // queryMonth:"",
      },

      form: {},
      selectList: [], // 多选数据
      exportData: [],
      exportModalVisible: false, // 自定义导出显示
      exportTitle: "确认导出",
      filename: "运单流向统计",
      loadingExport: true, // 导出加载状态\
      exportRemarks: "",
      chooseColumns: [],
      exportColumns: [
        {
          title: "#",
          key: "serialNumber",
          minWidth: 60,
          sortable: true,
        },
        {
          title: "装货地",
          key: "placeLoading",
          minWidth: 100,
          sortable: true,
        },
        {
          title: "卸货地",
          key: "placeDischarge",
          minWidth: 100,
          sortable: true,
        },
        {
          title: "订单数",
          key: "entrustedNum",
          minWidth: 100,
          sortable: true,
        },
        {
          title: "运单数",
          key: "orderNum",
          minWidth: 100,
          sortable: true,
        },
        {
          title: "装载吨数",
          key: "transGoodWeight",
          minWidth: 100,
          sortable: true,
        },
        {
          title: "签收吨数",
          key: "realGoodWeight",
          minWidth: 100,
          sortable: true,
        },
        {
          title: "合同运费",
          key: "estimateAmt",
          minWidth: 100,
          sortable: true,
        },
        // {
        //   title: "合同额占比",
        //   key: "mobile8",
        //   minWidth: 120,
        // },
        {
          title: "实结运费",
          key: "realOrderAmt",
          minWidth: 100,
          sortable: true,
        },
        // {
        //   title: "结算额占比",
        //   key: "mobile10",
        //   minWidth: 120,
        // },
      ],
      columns: [
        // 表头
        {
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          title: "#",
          type: "index",
          width: 60,
        },
        {
          title: "装货地",
          minWidth: 220,
          render: (h, params) => {
            let text =
              params.row.beginAreaVo.provinceName +
              params.row.beginAreaVo.cityName +
              params.row.beginAreaVo.areaName;
            let placTop = "top";
            if (params.index == 0) {
              placTop = "bottom";
            } else {
              placTop = "top";
            }
            return h(
              "Tooltip",
              {
                props: {
                  maxWidth: "220",
                  placement: placTop,
                  content: text,
                  transfer: true,
                },
              },
              [
                h(
                  "div",
                  {
                    style: {
                      display: "inline-block",
                      width: params.column._width * 0.8 + "px",
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                      whiteSpace: "nowrap",
                      marginTop: "9px",
                    },
                  },
                  text
                ),
              ]
            );
          },
        },
        {
          title: "卸货地",
          minWidth: 220,
          render: (h, params) => {
            let text =
              params.row.endAreaVo.provinceName +
              params.row.endAreaVo.cityName +
              params.row.endAreaVo.areaName;
            let placTop = "top";
            if (params.index == 0) {
              placTop = "bottom";
            } else {
              placTop = "top";
            }
            return h(
              "Tooltip",
              {
                props: {
                  maxWidth: "220",
                  placement: placTop,
                  content: text,
                  transfer: true,
                },
              },
              [
                h(
                  "div",
                  {
                    style: {
                      display: "inline-block",
                      width: params.column._width * 0.8 + "px",
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                      whiteSpace: "nowrap",
                      marginTop: "9px",
                    },
                  },
                  text
                ),
              ]
            );
          },
        },
        // {
        //   title: "订单数",
        //   key: "entrustedNum",
        //   minWidth: 100,
        //   render: (h, params) => {
        //     if (
        //       params.row.entrustedNum == null ||
        //       params.row.entrustedNum == ""
        //     ) {
        //       return h("div", 0 + " 单");
        //     } else {
        //       return h("div", params.row.entrustedNum + " 单");
        //     }
        //   },
        // },
        {
          title: "运单数",
          key: "orderNum",
          minWidth: 100,
          render: (h, params) => {
            if (params.row.orderNum == null || params.row.orderNum == "") {
              return h("div", 0 + " 单");
            } else {
              return h("div", params.row.orderNum + " 单");
            }
          },
        },
        {
          title: "装载吨数",
          key: "transGoodWeight",
          minWidth: 100,
          render: (h, params) => {
            if (
              params.row.transGoodWeight == null ||
              params.row.transGoodWeight == ""
            ) {
              return h("div", "--");
            } else {
              return h("div", params.row.transGoodWeight.toFixed(2) + " 吨");
            }
          },
        },
        {
          title: "签收吨数",
          key: "realGoodWeight",
          minWidth: 100,
          render: (h, params) => {
            if (
              params.row.realGoodWeight == null ||
              params.row.realGoodWeight == ""
            ) {
              return h("div", "--");
            } else {
              return h("div", params.row.realGoodWeight.toFixed(2) + " 吨");
            }
          },
        },
        {
          title: "合同运费",
          key: "estimateAmt",
          minWidth: 120,
          render: (h, params) => {
            if (
              params.row.estimateAmt == null ||
              params.row.estimateAmt == ""
            ) {
              return h("div", 0 + " 元");
            } else {
              return h("div", params.row.estimateAmt + " 元");
            }
          },
        },
        // {
        //   title: "合同额占比",
        //   key: "mobile8",
        //   minWidth: 120,
        // },
        {
          title: "实结运费",
          key: "realOrderAmt",
          minWidth: 120,
          render: (h, params) => {
            if (
              params.row.realOrderAmt == null ||
              params.row.realOrderAmt == ""
            ) {
              return h("div", 0 + " 元");
            } else {
              return h("div", params.row.realOrderAmt + " 元");
            }
          },
        },
        // {
        //   title: "结算额占比",
        //   key: "mobile10",
        //   minWidth: 120,
        // },
      ],
      data: [], // 表单数据
      pageNumber: 1, // 当前页数
      pageSize: 10, // 页面大小
      total: 0, // 表单数据总数
    };
  },
  methods: {
    init() {
      this.getDataList();
      this.getProvinceDataList();
      // 初始化导出列数据
      let array = [];
      this.exportColumns.forEach((e) => {
        // 指定列限制权限
        if (
          !this.getStore("roles").includes("ROLE_ADMIN") &&
          e.key == "mobile"
        ) {
          e.title = "[无权导出] " + e.title;
          e.disabled = true;
        } else {
          e.disabled = false;
        }
        array.push(e.title);
      });
      this.chooseColumns = array;
    },
    getProvinceDataList() {
      let fn = () => {
        getProvinceData().then((res) => {
          if (res.code == 200) {
            res.result.forEach(function (e) {
              e.level = 1;
              e.label = e.provinceName;
              e.pid = e.provinceCode;
              e.value = e.provinceCode;
              e.loading = false;
              e.children = [];
            });
            this.UnloadingAddresslist = res.result;
            // this.loadingData = res.result;
          } else {
            this.$Message.error(res.message);
          }
        });
      };
      fn();
    },
    // 搜索卸货详细地址
    ProvinceloadData(item, callback) {
      item.loading = true;
      getAreaCityList({ code: item.value, type: item.level }).then((res) => {
        item.loading = false;
        if (res.code == 200) {
          res.result.forEach(function (e) {
            if (e.level != 3) {
              e.level = e.level;
              e.label = e.label;
              e.pid = e.pid;
              e.value = e.value;
              e.loading = false;
              e.children = [];
            } else {
              e.value = e.value;
              e.label = e.label;
            }
          });
          item.children = res.result;
          callback();
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    //搜索装货详细地址
    LoadingProvinceloadData(item, callback) {
      this.$nextTick(() => {
        item.loading = true;
        getAreaCityList({ code: item.value, type: item.level }).then((res) => {
          item.loading = false;
          if (res.code == 200) {
            res.result.forEach(function (e) {
              if (e.level != 3) {
                e.level = e.level;
                e.label = e.label;
                e.pid = e.pid;
                e.value = e.value;
                e.loading = false;
                e.children = [];
              } else {
                e.value = e.value;
                e.label = e.label;
              }
            });
            item.children = res.result;
            callback();
          } else {
            this.$Message.error(res.message);
          }
        });
      });
    },
    // 选择装货地址
    getStartArea(value, selectedData) {
      if (selectedData.length == 3) {
        this.searchForm.beginAreaCode = value[2]; //搜索赋值
      }
    },
    // 选择卸货地址
    changeUnloading(value, selectedData) {
      if (selectedData.length == 3) {
        this.searchForm.endAreaCode = value[2]; //搜索赋值
      }
    },
    changeMonth() {
      let date = this.month;
      if (date) {
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        month = month < 10 ? "0" + month : month;
        let mydate = year.toString() + month.toString();
        this.searchForm.queryMonth = mydate;
      } else {
        this.searchForm.queryMonth = "";
      }
    },
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getDataList();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getDataList();
    },
    handleSearch() {
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.getDataList();
    },
    handleReset() {
      // this.$refs.searchForm.resetFields();
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.searchForm.beginAreaCode = "";
      this.searchForm.endAreaCode = "";
      this.searchForm.UnloadingAddress = "";
      this.searchForm.LoadingAddress = "";
      this.month = "";
      this.begin = [];
      this.end = [];
      this.searchForm.queryMonth = "";
      // 重新加载数据
      this.getDataList();
    },
    changeSelect(e) {
      this.selectList = e;
      this.exportData = e;
      this.exportData.forEach((item, index) => {
        // 序号
        item.serialNumber = index + 1;
        // 装货地
        if (item.beginAreaVo) {
          item.placeLoading =
            item.beginAreaVo.provinceName +
            item.beginAreaVo.cityName +
            item.beginAreaVo.areaName;
        }
        // 卸货地
        if (item.endAreaVo) {
          item.placeDischarge =
            item.endAreaVo.provinceName +
            item.endAreaVo.cityName +
            item.endAreaVo.areaName;
        }
        // 订单数
        if (item.entrustedNum) {
          item.entrustedNum = item.entrustedNum + " 单";
        }
        // 运单数
        if (item.orderNum) {
          item.orderNum = item.orderNum + " 单";
        }
        // 装载吨数
        if (item.transGoodWeight) {
          item.transGoodWeight = item.transGoodWeight.toFixed(2) + " 吨";
        }
        // 签收吨数
        if (item.realGoodWeight) {
          item.realGoodWeight = item.realGoodWeight.toFixed(2) + " 吨";
        }
        // 合同运费
        if (item.estimateAmt) {
          item.estimateAmt = item.estimateAmt.toFixed(2) + " 元";
        }
        // 实结运费
        if (item.realOrderAmt) {
          item.realOrderAmt = item.realOrderAmt.toFixed(2) + " 元 ";
        }
      });
    },
    exportSelectData() {
      if (this.selectList.length <= 0) {
        this.$Message.warning("您还未选择要导出的数据");
        return;
      }
      this.exportType = "part";
      this.exportModalVisible = true;
      this.exportTitle = "确认导出 " + this.selectList.length + " 条数据";
      this.exportRemarks = "";
    },
    exportCustomData() {
      // 上传记录
      let param = new FormData(); // 创建form对象
      // param.append("file", a); // 通过append向form对象添加数据
      param.append("fileName", this.filename); // 添加form表单中其他数据
      param.append("fileType", 7); // 通过append向form对象添加数据
      param.append("remarks", this.exportRemarks); // 添加form表单中其他数据
      addDownloadRecord(param).then((res) => {
        if (res.code == 200) {
          // 判断勾选导出列
          let array = [];
          this.exportColumns.forEach((e) => {
            this.chooseColumns.forEach((c) => {
              if (e.title == c && !e.disabled) {
                array.push(e);
              }
            });
          });
          let filename = res.result + " " + this.filename;
          this.exportColumns = array;
          this.exportModalVisible = false;
          let title = [];
          let key = [];
          this.exportColumns.forEach((e) => {
            title.push(e.title);
            key.push(e.key);
          });
          const params = {
            title: title,
            key: key,
            data: this.exportData,
            autoWidth: true,
            filename: filename,
          };
          excel.export_array_to_excel(params);
        } else {
          return this.$Message.error(res.message);
        }
      });
    },
    getDataList() {
      this.loading = true;
      if (this.searchForm.LoadingAddress.length > 0) {
      } else {
        this.searchForm.beginAreaCode = "";
      }
      if (this.searchForm.UnloadingAddress.length > 0) {
      } else {
        this.searchForm.endAreaCode = "";
      }
      getAreaOrderSumVo(this.searchForm).then((res) => {
        this.loading = false;
        if (res.success) {
          this.data = res.result.records;
          this.total = res.result.total;
          if (this.data.length == 0 && this.searchForm.pageNumber > 1) {
            this.searchForm.pageNumber -= 1;
            this.getDataList();
          }
        }
      });
    },
  },
  mounted() {
    this.init();
  },
};
</script>
<style lang="less">
.Unloadingcss {
  .ivu-cascader-menu {
    min-width: 155px !important;
  }
}
</style>